import re
import sys
import os
import csv

# 从 CSV 文件中读取省份编码与名称映射
province_dict = {}
# 当前脚本所在目录
current_dir = os.path.dirname(os.path.abspath(__file__))
province_csv_path = os.path.join(current_dir, 'province.csv')
try:
    with open(province_csv_path, 'r', encoding='utf-8') as file:
        reader = csv.reader(file)
        next(reader)  # 跳过标题行
        for row in reader:
            code, name = row
            province_dict[code] = name
except FileNotFoundError:
    print(f"错误: 未找到 {province_csv_path} 文件!")
    sys.exit(1)

# 从 CSV 文件中读取详细地址编码与名称映射
address_dict = {}
address_csv_path = os.path.join(current_dir, 'address.csv')
try:
    with open(address_csv_path, 'r', encoding='utf-8') as file:
        reader = csv.reader(file)
        next(reader)  # 跳过标题行
        for row in reader:
            code, name = row
            address_dict[code] = name
except FileNotFoundError:
    print(f"错误: 未找到 {address_csv_path} 文件!")
    sys.exit(1)

# 正则表达式模式
id_pattern = re.compile(r'^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[0-9Xx]$')

while True:
    id_number = input("请输入身份证号：")
    if id_pattern.match(id_number):
        # 获取省份编码
        province_code = id_number[:2]
        province = province_dict.get(province_code, '未知省份')

        # 获取详细地址
        address_code = id_number[:6]
        address = address_dict.get(address_code, '未知地区')

        # 获取出生年月日
        birth_year = id_number[6:10]
        birth_month = id_number[10:12]
        birth_day = id_number[12:14]

        print(f"身份证号合规，所在地址：{province}{address}，出生年月日：{birth_year}年{birth_month}月{birth_day}日")
        break
    else:
        print("输入的身份证号不合规，请重新输入。")
